using System;
using MySql.Data.MySqlClient;
using System.Windows;
using System.Windows.Forms;
using MessageBox = System.Windows.MessageBox;
using System.Windows.Input;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Threading;

namespace MainUI
{
    public partial class MainWindow : Window
    {
        private RealTimeFileMonitor _fileMonitor; // 监控图片保存文件夹

        public MainWindow()
        {
            InitializeComponent();
            HotkeyManager.Initialize(this);
            Loaded += OnLoaded;
            Closed += OnClosed;
        }

        private void SetSavePicPosButton_Click(object sender, RoutedEventArgs e)
        {
            using (var folderBrowser = new FolderBrowserDialog())
            {
                folderBrowser.Description = "请选择用于存储文件的文件夹";
                var result = folderBrowser.ShowDialog();

                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    SavePicBox.Text = folderBrowser.SelectedPath;
                }
                else
                {
                    MessageBox.Show(
                        "未选择任何文件夹",
                        "提示",
                        MessageBoxButton.OK,
                        MessageBoxImage.Warning
                    );
                }
            }

            //数据库连接
            const string connectionString = "Server=localhost;Port=3306;Database=screenpic;Uid=root;Pwd=hjj1019583787;";

            const string createTableSql = @"
CREATE TABLE IF NOT EXISTS screenshots (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    file_name VARCHAR(255) NOT NULL,
    file_path VARCHAR(512) NOT NULL,
    file_format VARCHAR(20) NOT NULL,
    capture_width INT NOT NULL,
    capture_height INT NOT NULL,
    capture_area VARCHAR(50),
    create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    last_modify_time DATETIME,
    is_deleted TINYINT NOT NULL DEFAULT 0,
    parent_screenshot BIGINT,
    FOREIGN KEY (parent_screenshot) REFERENCES screenshots(id)
) ENGINE=InnoDB;";

            try
            {
                using (var connection = new MySqlConnection(connectionString))
                {
                    connection.Open();
                    using (var command = new MySqlCommand(createTableSql, connection))
                    {
                        command.ExecuteNonQuery();
                    }
                }
               // MessageBox.Show("数据库连接成功，表结构初始化完成", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"数据库操作失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }


        private int _fixedHotkeyId = -1;
        private int _customHotkeyId = -1;

        private void SetPRSCButton_Click(object sender, RoutedEventArgs e)
        {
            var settingsWindow = new HotkeySettingsWindow();
            if (settingsWindow.ShowDialog() == true)
            {
                RegisterHotkeys();
            }
        }

        private void RegisterHotkeys()
        {
            if (!string.IsNullOrEmpty(Properties.Settings.Default.FixedHotkey))
            {
                var (fixedMod, fixedKey) = ParseHotkey(Properties.Settings.Default.FixedHotkey);
                _fixedHotkeyId = HotkeyManager.Register(fixedMod, fixedKey, CaptureFixedScreenshot);
            }

            if (!string.IsNullOrEmpty(Properties.Settings.Default.CustomHotkey))
            {
                var (customMod, customKey) = ParseHotkey(Properties.Settings.Default.CustomHotkey);
                _customHotkeyId = HotkeyManager.Register(customMod, customKey, CaptureCustomScreenshot);
            }
        }

        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            try
            {
                var (fixedMod, fixedKey) = ParseHotkey(Properties.Settings.Default.FixedHotkey);
                _fixedHotkeyId = HotkeyManager.Register(fixedMod, fixedKey, CaptureFixedScreenshot);

                var (customMod, customKey) = ParseHotkey(Properties.Settings.Default.CustomHotkey);
                _customHotkeyId = HotkeyManager.Register(customMod, customKey, CaptureCustomScreenshot);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "热键初始化失败", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void OnClosed(object sender, EventArgs e)
        {
            if (_fixedHotkeyId != -1) HotkeyManager.Unregister(_fixedHotkeyId);
            if (_customHotkeyId != -1) HotkeyManager.Unregister(_customHotkeyId);

            // 停止文件监控
            if (_fileMonitor != null)
            {
                _fileMonitor.StopMonitoring();
            }
        }

        private (ModifierKeys modifiers, Key key) ParseHotkey(string hotkey)
        {
            if (string.IsNullOrEmpty(hotkey)) throw new ArgumentException("空快捷键配置");

            var parts = hotkey.Split(new[] { "+" }, StringSplitOptions.RemoveEmptyEntries)
                             .Select(p => p.Trim())
                             .ToArray();

            ModifierKeys mods = ModifierKeys.None;
            Key finalKey = Key.None;

            foreach (var part in parts.Take(parts.Length - 1))
            {
                switch (part.ToUpper())
                {
                    case "CTRL": mods |= ModifierKeys.Control; break;
                    case "ALT": mods |= ModifierKeys.Alt; break;
                    case "SHIFT": mods |= ModifierKeys.Shift; break;
                    case "WIN": mods |= ModifierKeys.Windows; break;
                    default: throw new FormatException($"无效的修饰键: {part}");
                }
            }

            if (!Enum.TryParse(parts.Last(), true, out finalKey))
            {
                throw new FormatException($"无效的按键: {parts.Last()}");
            }

            return (mods, finalKey);
        }

        private void CaptureFixedScreenshot()
        {
            try
            {
                var size = Properties.Settings.Default.AreaSize.Split(',')
                    .Select(int.Parse).ToArray();

                if (size.Length != 2) throw new InvalidOperationException("无效的截图尺寸配置");

                var screen = System.Windows.Forms.Screen.PrimaryScreen.Bounds;
                using (var bitmap = new System.Drawing.Bitmap(size[0], size[1]))
                using (var graphics = System.Drawing.Graphics.FromImage(bitmap))
                {
                    graphics.CopyFromScreen(
                        screen.Width / 2 - size[0] / 2,
                        screen.Height / 2 - size[1] / 2,
                        0, 0,
                        new System.Drawing.Size(size[0], size[1])
                    );

                    SaveScreenshot(bitmap);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"固定截图失败: {ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void CaptureCustomScreenshot()
        {
            try
            {
                var regionSelector = new RegionSelectorWindow();
                if (regionSelector.ShowDialog() == true)
                {
                    var rect = regionSelector.SelectedRegion;
                    using (var bitmap = new System.Drawing.Bitmap((int)rect.Width, (int)rect.Height))
                    using (var graphics = System.Drawing.Graphics.FromImage(bitmap))
                    {
                        graphics.CopyFromScreen(
                            (int)rect.Left,
                            (int)rect.Top,
                            0, 0,
                            new System.Drawing.Size((int)rect.Width, (int)rect.Height)
                        );

                        SaveScreenshot(bitmap);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"区域截图失败: {ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void SaveScreenshot(System.Drawing.Bitmap bitmap)
        {
            // 检查保存路径是否有效
            if (string.IsNullOrWhiteSpace(SavePicBox.Text))
            {
                MessageBox.Show("请先选择图片存储路径", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            try
            {
                // 生成文件名和完整路径
                string fileName = $"Screenshot_{DateTime.Now:yyyyMMddHHmmss}.png";
                string saveDir = SavePicBox.Text.Trim();
                string savePath = Path.Combine(saveDir, fileName);

                // 确保目录存在
                Directory.CreateDirectory(saveDir);

                // 保存图片文件
                bitmap.Save(savePath, System.Drawing.Imaging.ImageFormat.Png);

                // 数据库连接信息
                const string connectionString = "Server=localhost;Port=3306;Database=screenpic;Uid=root;Pwd=hjj1019583787;";

                // 插入数据库记录
                using (var connection = new MySqlConnection(connectionString))
                {
                    connection.Open();

                    const string insertSql = @"
INSERT INTO screenshots 
    (file_name, file_path, file_format, capture_width, capture_height, create_time)
VALUES
    (@name, @path, @format, @width, @height, @createTime)";

                    using (var cmd = new MySqlCommand(insertSql, connection))
                    {
                        cmd.Parameters.AddWithValue("@name", fileName);
                        cmd.Parameters.AddWithValue("@path", savePath);
                        cmd.Parameters.AddWithValue("@format", "PNG");
                        cmd.Parameters.AddWithValue("@width", bitmap.Width);
                        cmd.Parameters.AddWithValue("@height", bitmap.Height);
                        cmd.Parameters.AddWithValue("@createTime", DateTime.Now);

                        int affectedRows = cmd.ExecuteNonQuery();

                        if (affectedRows > 0)
                        {
                            // 假设这是保存截图后的逻辑
                            if (CheckTipsBox.IsChecked == true)
                            {
                                MessageBox.Show($"截图已保存至: {savePath}\n数据库记录已更新", "完成",
                                                MessageBoxButton.OK, MessageBoxImage.Information);
                            }
                        }
                        else
                        {
                            MessageBox.Show("图片保存成功，但数据库写入失败", "警告",
                                MessageBoxButton.OK, MessageBoxImage.Warning);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败: {ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {

        }

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {

        }
    }
}